package com.tianji.learning.utils;


import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Data
public class DelayTask<D> implements Delayed {


    private Long deadLineNacos;//延时执行时间的纳秒值
    private D data;//延时任务数据

    public DelayTask(Duration duration, D data) {
        this.deadLineNacos = System.nanoTime()+duration.toNanos();
        this.data = data;
    }

    /**
     * 1 用于获取队列中每个任务 距离当前时间还有多久【纳秒】
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNacos - System.nanoTime(), 0),TimeUnit.NANOSECONDS);
    }

    /**
     *2 对延迟队列中的任务进行排序 【排序依据】：根据getDelay获取的任务延迟时间进行排序，值越小，越先被执行
     */
    @Override
    public int compareTo(Delayed o) {
        long diff =this.getDelay(TimeUnit.NANOSECONDS)-o.getDelay(TimeUnit.NANOSECONDS);
        if (diff > 0){
            return 1;
        }else if (diff == 0){
            return 0;
        }else {
            return -1;
        }
    }
}
